const { app, BrowserWindow, ipcMain, dialog } = require('electron')
const path = require('path')
const fs = require('fs-extra')
const { M3U8Downloader } = require('./m3u8-downloader')
const ffmpeg = require('fluent-ffmpeg')

// 强制设置开发环境
if (!process.env.NODE_ENV) {
  process.env.NODE_ENV = 'development'
}

let mainWindow
let downloader

// 创建主窗口
function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1400,
    height: 900,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    },
    icon: path.join(__dirname, 'icon.png'),
    show: false
  })

  // 加载应用
  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:3000')
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  // 窗口准备好后显示
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })

  // 窗口关闭时清理资源
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

// 应用准备就绪时创建窗口
app.whenReady().then(async () => {
  createWindow()
  
  // 初始化下载器
  const downloadPath = path.join(app.getPath('downloads'), 'm3u8-downloads')
  console.log('Initializing downloader with path:', downloadPath)
  
  try {
    downloader = new M3U8Downloader(downloadPath)
    console.log('Downloader instance created')
    
    // 等待下载器完全初始化
    await downloader.ensureDownloadPath()
    console.log('Downloader initialized successfully')
    
    // 设置事件监听
    downloader.on('progress', (data) => {
      if (mainWindow && !mainWindow.isDestroyed()) {
        console.log('Sending progress event to renderer:', {
          taskId: data.taskId,
          status: data.status,
          progress: data.progress,
          downloadedSize: data.downloadedSize,
          totalSize: data.totalSize,
          downloadedSegments: data.downloadedSegments,
          totalSegments: data.totalSegments
        })
        mainWindow.webContents.send('download-progress', data)
      } else {
        console.warn('Main window not available for progress event')
      }
    })
    
    downloader.on('completed', (data) => {
      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.webContents.send('download-completed', data)
      } else {
        console.warn('Main window not available for completed event')
      }
    })
    
    downloader.on('error', (data) => {
      if (mainWindow && !mainWindow.isDestroyed()) {
        mainWindow.webContents.send('download-error', data)
      } else {
        console.warn('Main window not available for error event')
      }
    })
    
    console.log('Downloader event listeners set up successfully')
  } catch (error) {
    console.error('Failed to initialize downloader:', error)
    downloader = null
  }
})

// 所有窗口关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// IPC 处理程序
ipcMain.handle('start-download', async (event, config) => {
  try {
    console.log('Starting download with config:', config)
    
    if (!downloader) {
      throw new Error('Downloader not initialized')
    }
    
    console.log('Calling downloader.startDownload...')
    const result = await downloader.startDownload(config)
    console.log('downloader.startDownload result:', result)
    
    // 现在 startDownload 立即返回 taskId
    return { 
      success: true, 
      data: {
        taskId: result.taskId
      }
    }
  } catch (error) {
    console.error('IPC start-download error:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('pause-download', async (event, taskId) => {
  try {
    await downloader.pauseDownload(taskId)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('resume-download', async (event, taskId) => {
  try {
    await downloader.resumeDownload(taskId)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('get-download-status', async (event, taskId) => {
  try {
    const status = await downloader.getDownloadStatus(taskId)
    return { success: true, data: status }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 新增的IPC处理方法
ipcMain.handle('get-task-list', async () => {
  try {
    if (!downloader) {
      return { success: false, error: 'Downloader not initialized' }
    }
    
    const taskList = await downloader.getAllTasks()
    return { success: true, data: taskList }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('sync-task-status', async (event, taskId, status) => {
  try {
    if (!downloader) {
      return { success: false, error: 'Downloader not initialized' }
    }
    
    const result = await downloader.syncTaskStatus(taskId, status)
    return { success: result }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('delete-task', async (event, taskId) => {
  try {
    if (!downloader) {
      return { success: false, error: 'Downloader not initialized' }
    }
    
    const task = downloader.tasks.get(taskId)
    if (task) {
      console.log(`Deleting task: ${taskId}, status: ${task.status}`)
      
      // 如果任务正在运行，先强制停止
      if (['downloading', 'merging', 'parsing'].includes(task.status)) {
        try {
          await downloader.forceStopTask(taskId)
          console.log(`Task ${taskId} force stopped for deletion`)
        } catch (stopError) {
          console.warn(`Failed to force stop task ${taskId}:`, stopError.message)
          // 即使停止失败，也继续删除
        }
      }
      
      // 删除任务
      downloader.tasks.delete(taskId)
      console.log(`Task ${taskId} removed from memory`)
      
      // 清理临时文件
      const taskDir = path.join(downloader.downloadPath, taskId)
      try {
        if (await fs.pathExists(taskDir)) {
          await fs.remove(taskDir)
          console.log(`Task directory ${taskDir} cleaned up`)
        }
      } catch (cleanupError) {
        console.warn('Failed to cleanup task directory:', cleanupError.message)
        // 即使清理失败，也返回成功，因为任务已经从内存中删除
      }
      
      return { success: true, message: 'Task deleted successfully' }
    } else {
      console.warn(`Task ${taskId} not found in memory`)
      // 即使任务不在内存中，也尝试清理目录
      const taskDir = path.join(downloader.downloadPath, taskId)
      try {
        if (await fs.pathExists(taskDir)) {
          await fs.remove(taskDir)
          console.log(`Orphaned task directory ${taskDir} cleaned up`)
        }
      } catch (cleanupError) {
        console.warn('Failed to cleanup orphaned task directory:', cleanupError.message)
      }
      
      return { success: true, message: 'Task not found but cleanup attempted' }
    }
  } catch (error) {
    console.error('Delete task error:', error)
    return { success: false, error: error.message }
  }
})

ipcMain.handle('retry-task', async (event, taskId) => {
  try {
    if (!downloader) {
      return { success: false, error: 'Downloader not initialized' }
    }
    
    const task = downloader.tasks.get(taskId)
    if (!task) {
      return { success: false, error: 'Task not found' }
    }
    
    // 重新开始下载
    const result = await downloader.startDownload({
      url: task.url,
      filename: task.filename,
      outputPath: task.outputPath,
      concurrentThreads: task.concurrentThreads,
      retryCount: task.maxRetries
    })
    
    return { success: true, data: { taskId: result.taskId } }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 格式转换
ipcMain.handle('convert-format', async (event, inputFile, outputFormat, options = {}) => {
  try {
    if (!downloader) {
      return { success: false, error: 'Downloader not initialized' }
    }
    
    const result = await downloader.convertFormat(inputFile, outputFormat, options)
    return { success: true, data: result }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 调试接口
ipcMain.handle('debug-task', async (event, taskId) => {
  try {
    if (!downloader) {
      return { success: false, error: 'Downloader not initialized' }
    }
    
    await downloader.debugSegments(taskId)
    return { success: true, message: 'Debug completed, check console for details' }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 调试删除功能
ipcMain.handle('debug-delete', async (event, taskId) => {
  try {
    if (!downloader) {
      return { success: false, error: 'Downloader not initialized' }
    }
    
    await downloader.debugDelete(taskId)
    return { success: true, message: 'Delete debug completed, check console for details' }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 获取FFmpeg版本信息
ipcMain.handle('get-ffmpeg-info', async () => {
  try {
    const ffmpegPath = ffmpeg.path
    const version = await new Promise((resolve, reject) => {
      ffmpeg.getAvailableFormats((err, formats) => {
        if (err) {
          reject(err)
        } else {
          resolve('FFmpeg available')
        }
      })
    })
    
    return { 
      success: true, 
      data: { 
        path: ffmpegPath, 
        version: version 
      } 
    }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 检查下载器状态
ipcMain.handle('check-downloader-status', async () => {
  try {
    return { 
      success: true, 
      data: { 
        initialized: !!downloader && downloader.initialized,
        downloaderExists: !!downloader,
        downloadPath: downloader ? downloader.downloadPath : null,
        taskCount: downloader ? downloader.tasks.size : 0,
        initializationStatus: downloader ? (downloader.initialized ? 'completed' : 'pending') : 'not_created'
      } 
    }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 选择目录
ipcMain.handle('select-directory', async () => {
  try {
    const result = await dialog.showOpenDialog(mainWindow, {
      properties: ['openDirectory'],
      title: '选择下载目录'
    })
    
    if (!result.canceled && result.filePaths.length > 0) {
      return { success: true, data: { path: result.filePaths[0] } }
    } else {
      return { success: false, error: '用户取消了选择' }
    }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 打开文件
ipcMain.handle('open-file', async (event, filePath) => {
  try {
    if (!await fs.pathExists(filePath)) {
      return { success: false, error: '文件不存在' }
    }
    
    const { shell } = require('electron')
    await shell.openPath(filePath)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

// 打开文件所在位置
ipcMain.handle('open-file-location', async (event, filePath) => {
  try {
    if (!await fs.pathExists(filePath)) {
      return { success: false, error: '文件不存在' }
    }
    
    const { shell } = require('electron')
    await shell.showItemInFolder(filePath)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
}) 